package com.woniuxy.repair.controller;

import com.woniuxy.common.dto.OwnerDto;
import com.woniuxy.common.dto.WcnUserDto;
import com.woniuxy.repair.pojo.RepairOrder;
import com.woniuxy.repair.feign.BaoxiuFeign;
import com.woniuxy.repair.service.RepairOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.woniuxy.common.utils.UserUtil.getUser1;
import static com.woniuxy.common.utils.UserUtil.getUser2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
public class RepairOrderController {
    private static final Logger log = LoggerFactory.getLogger(RepairOrderController.class);

    @Autowired
    private RepairOrderService repairOrderService;
    @Autowired
    private BaoxiuFeign baoxiuFeign;

    //获取待审批报修单
    @GetMapping("/property")
    public List<RepairOrder> property() {
        return repairOrderService.property();
    }
    @GetMapping("/repairByOwnerId")
    public List<RepairOrder> repairByOwnerId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpRequest = attributes.getRequest();
        String token = httpRequest.getHeader("Authorization");
        OwnerDto user = getUser1(token);
        String userId = user.getId().toString();
        return repairOrderService.lambdaQuery()
                .eq(RepairOrder::getOwnerId, userId)
                .list();
    }

    //新增一个保修单
    @ResponseBody
    @PostMapping("/submitRepair")
    public ResponseEntity<Map<String, Object>> submitRepair(@RequestBody RepairOrder repairOrder){
        try {
        RepairOrder repairOrder1 = repairOrderService.addRepair(repairOrder);
        log.info("新建报修单，repairOrder1: {}", repairOrder1);
            
            // 构建请求参数
            Map<String, Object> request = new HashMap<>();
            request.put("repairOrderId", repairOrder1.getId());
            request.put("yezhu", repairOrder1.getOwnerId());
            request.put("wuye", 2L);
            request.put("weixiu", 3L);
            request.put("description", repairOrder1.getDescription());
            
            ResponseEntity<Map<String, Object>> response = baoxiuFeign.startRepairFlow(request);
            log.info("调用工作流返回: {}", response.getBody());
            
            // 获取流程实例ID并更新到订单中
            String processInstanceId = null;
            if (response.getBody() != null) {
                processInstanceId = (String) response.getBody().get("processInstanceId");
            }
            log.info("获取到流程实例ID: {}", processInstanceId);
            log.info("repairOrder1 id: {}", repairOrder1.getId());
            // 更新订单的orderNo字段为processInstanceId
            if (processInstanceId != null) {
                repairOrder1.setOrderNo(processInstanceId);
                boolean updated = repairOrderService.updateById(repairOrder1);
                log.info("更新订单流程实例ID结果: {}", updated);
            } else {
                log.warn("未获取到流程实例ID，订单未更新");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("repairOrder", repairOrder1);
            result.put("processInstanceId", processInstanceId);
            result.put("message", "报修单提交成功，流程已启动");

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("报修单提交异常", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "报修单提交失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查看流程图
     */
    @GetMapping("/process/diagram/{processInstanceId}")
    public void getProcessDiagram(@PathVariable String processInstanceId, HttpServletResponse response) {
        try {
            baoxiuFeign.getProcessDiagram(processInstanceId, response);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("{\"error\": \"" + e.getMessage() + "\"}");
            } catch (Exception ignored) {}
        }
    }

    /**
     * 获取流程实例信息
     */
    @GetMapping("/process/{processInstanceId}")
    public ResponseEntity<Map<String, Object>> getProcessInstance(@PathVariable String processInstanceId) {
        try {
            ResponseEntity<Map<String, Object>> response = baoxiuFeign.getProcessInstance(processInstanceId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            if (response.getBody() != null) {
                result.put("processInfo", response.getBody());
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取流程实例失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 物业审批报修单
     */
    @PostMapping("/{repairOrderId}/approve")
    public ResponseEntity<Map<String, Object>> approveRepair(
            @PathVariable Long repairOrderId,
            @RequestBody Map<String, Object> request) {
        try {
            // 从请求体中获取参数
            Boolean approved = Boolean.valueOf(request.get("approved").toString());
            String comment = request.get("comment") != null ? request.get("comment").toString() : null;
            
            // 从token获取用户ID
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest httpRequest = attributes.getRequest();
            String token = httpRequest.getHeader("Authorization");
//            OwnerDto user = getUser1(token);
            WcnUserDto wcnUserDto = getUser2(token);
            String userId = wcnUserDto.getRoleId().toString();
            
            // 先调用工作流审批
            Map<String, Object> flowRequest = new HashMap<>();
            flowRequest.put("approved", approved);
            flowRequest.put("comment", comment);
            flowRequest.put("userId", userId);
            baoxiuFeign.approveRepairFlow(repairOrderId, flowRequest);
            
            // 再更新业务表状态
            repairOrderService.approveRepair(repairOrderId, approved, comment);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", approved ? "审批通过成功" : "审批驳回成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "审批失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 维修人员处理报修单
     */
    @PostMapping("/{repairOrderId}/handle")
    public ResponseEntity<Map<String, Object>> handleRepair(
            @PathVariable Long repairOrderId,
            @RequestBody Map<String, Object> request) {
        try {
            // 从请求体中获取参数
            String feedback = request.get("feedback") != null ? request.get("feedback").toString() : null;
            Boolean completed = Boolean.valueOf(request.get("completed").toString());
            String repairResult = request.get("repairResult") != null ? request.get("repairResult").toString() : null;
            
            // 从token获取用户ID
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest httpRequest = attributes.getRequest();
            String token = httpRequest.getHeader("Authorization");
            WcnUserDto wcnUserDto = getUser2(token);
            String userId = wcnUserDto.getRoleId().toString();
//            OwnerDto user = getUser1(token);
//            String userId = user.getId().toString();
            
            // 先调用工作流处理
            Map<String, Object> flowRequest = new HashMap<>();
            flowRequest.put("completed", completed);
            flowRequest.put("feedback", feedback);
            flowRequest.put("repairResult", repairResult);
            flowRequest.put("userId", userId);
            baoxiuFeign.handleRepairFlow(repairOrderId, flowRequest);
            
            // 再更新业务表状态
            repairOrderService.handleRepair(repairOrderId, completed, feedback, repairResult);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", completed ? "维修完成" : "维修处理中");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "维修处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询维修人员的待处理任务
     */
    @GetMapping("/repair/tasks")
    public ResponseEntity<Map<String, Object>> getRepairTasks() {
        try {
            // 从token获取用户ID
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest httpRequest = attributes.getRequest();
            String token = httpRequest.getHeader("Authorization");
            OwnerDto user = getUser1(token);
            String userId = user.getId().toString();
            
            ResponseEntity<Map<String, Object>> response = baoxiuFeign.getRepairTasks(userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            if (response.getBody() != null) {
                result.put("tasks", response.getBody().get("tasks"));
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "查询维修任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    // 删除业主评价相关接口和逻辑
}
